package cn.conac.rc.auth.service;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import cn.conac.rc.auth.entity.UserEntity;
import cn.conac.rc.auth.repository.UserRepository;
import cn.conac.rc.auth.vo.UserVo;
import cn.conac.rc.framework.jpa.Criteria;
import cn.conac.rc.framework.jpa.Restrictions;
import cn.conac.rc.framework.service.GenericService;

@Service
public class UserService extends GenericService<UserEntity, String> {
	@Autowired
	private UserRepository userRepository;

	/**
	 * 获取用户
	 * @param id
	 * @return
	 */
	public UserEntity findById(String id){
		return userRepository.findById(id);
	}

	/**
	 * 获取用户
	 * @param loginName
	 * @return
	 */
	public UserEntity findByLoginName(String loginName){
		return userRepository.findByLoginName(loginName);
	}

	/**
	 * 获取用户
	 * @param siCode
	 * @return
	 */
	public List<UserEntity> findBySiUserCodeFullname(String siCode,String sullName){
		return userRepository.findBySiUserCodeFullname(siCode,sullName);
	}
	/**
	 * 获取用户
	 * @param siCode
	 * @return
	 */
	public List<UserEntity> findBySiUserCode(String siCode){
		return userRepository.findBySiUserCode(siCode);
	}
	/**
	 * 查询用户列表
	 * @param user
	 * @return
	 * @throws Exception
	 */
	public Page<UserEntity> list(UserVo user) throws Exception {
        try {
            Pageable pageable = new PageRequest(user.getPage(), user.getSize());
            Criteria<UserEntity> dc = this.createCriteria(user);
            return userRepository.findAll(dc, pageable);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
	
	/**
	 * 拼接查询条件
	 * 
	 * @param user
	 *            信息
	 * @return Criteria<UserEntity> JPA封装类
	 * @author haocm
	 */
	private Criteria<UserEntity> createCriteria(UserEntity user) {
		Criteria<UserEntity> dc = new Criteria<UserEntity>();
		if (StringUtils.isNotBlank(user.getLoginName())) {
			dc.add(Restrictions.like("loginName", user.getLoginName(), true));
		}
		return dc;
	}
	
}

